package com.example.lib.extend

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.util.TypedValue
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.example.lib.utils.net.NetUtils


fun Context?.getResourceColor(@ColorRes color: Int): Int {
    this?.let {
        return ContextCompat.getColor(this, color)
    } ?: let {
        return 0
    }
}

fun Context.dip2px(dpValue: Float): Int {
    val scale: Float = resources.displayMetrics.density
    return (dpValue * scale + 0.5f).toInt()
}

fun Context.px2dip(pxValue: Float): Float {
    val scale = resources.displayMetrics.density
    return (pxValue / scale + 0.5f)
}

fun Context.sp2px(spValue: Int): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue.toFloat(), resources.displayMetrics).toInt()
}

//注册网络监听回调
fun Context.registerNetWorkCallback(netUtils: NetUtils) {
    val request = NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build()
    val connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
    connMgr?.registerNetworkCallback(request, netUtils)
}

//取消网络监听回调
fun Context.unregisterNetWorkCallback(netUtils: NetUtils) {
    val connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
    connMgr?.unregisterNetworkCallback(netUtils)
}
